import os
import uuid
from time import sleep

from submodules.common.lib.platform_ import is_windows
from submodules.common.lib.local_paths import project_tmp_images_path
from submodules.common.lib.datetime_ import get_timestamp, get_timestamp_ms
from submodules.common.lib.log_ import logger
logger =get_logger()
from submodules.common.lib import adb_


class Device():
    def __init__(self, serial_number=None):
        if serial_number is None:
            self.serial_number = adb_.get_device_list()[0][0]
        else:
            self.serial_number = serial_number

    def tap(self, x, y):
        logger.info(f"tap() {x},{y}")
        os.system(f'adb -s{self.serial_number} shell input tap {x} {y}')

    def screencap(self, path_computer=None, path_device=f"/sdcard/screen_tmp_{get_timestamp()}.png",
                  image_path_out_suffix=""):
        '''
        device.screencap(os.path.join(current_dir))
        device.screencap(os.path.join(current_dir, "test.png"))
        '''
        if path_computer == None:
            path_computer = os.path.join(project_tmp_images_path,
                                         get_timestamp_ms() + "-" + image_path_out_suffix + "-" + str(
                                             uuid.uuid1()) + ".png")
        os.system(f"adb -s{self.serial_number} shell screencap -p {path_device}")
        os.system(f"adb -s{self.serial_number} pull {path_device} {path_computer}")
        return path_computer

    def start(self, package_name, activity_name):
        cmd_str = f"adb -s{self.serial_number} shell am start {package_name}/{activity_name}"
        os.system(cmd_str)

    def stop(self, package_name):
        cmd_str = f"adb -s{self.serial_number} shell am force-stop {package_name}"
        os.system(cmd_str)

    def grep(self, package_name_partial):
        res_list = []
        cmd_str = f'adb -s {self.serial_number} shell "ps | grep {package_name_partial}"'
        res = os.popen(cmd_str).readlines()
        for item in res:
            tmp_list = item.strip().split(" ")
            tmp_list2 = []
            for item in tmp_list:
                if len(item) != 0:
                    tmp_list2.append(item)
            res_list.append(tmp_list2)
        return res_list

    def clear(self, package_name):
        os.system(f"adb -s {self.serial_number} shell pm clear {package_name}")

    def install(self, file_path):
        cmd_str = f'adb -s {self.serial_number} install {file_path}'
        print(cmd_str)
        os.system(cmd_str)

    def uninstall(self, package_name):
        cmd_str = f'adb -s {self.serial_number} uninstall {package_name}'
        print(cmd_str)
        os.system(cmd_str)

    def is_app_alive(self, package_name):
        res = self.grep(package_name)
        if len(res) > 0:
            return True
        else:
            return False


    def get_current_activity(self, package_name):
        if is_windows():
            cmd_str = f'adb shell dumpsys activity | findstr mFocusedActivity'
        else:
            cmd_str = None
        res_str = os.popen(cmd_str).readlines()[0]
        list_tmp = res_str.strip().split(" ")[3].split("/")
        package_name = list_tmp[0]
        activity_name = list_tmp[1]
        return activity_name

    def click_by_text(self, target_text, page_text=None, evidence_text=None, seq_num=1, evidence_mode="hard",
                      engine="easyocr"):
        if evidence_text == None:
            evidence_text = target_text

        is_valid = False

        if page_text == None:
            # 获取当前截图
            img_path = self.screencap()
            # 获取位置
            page_text = self.get_page_text(engine)

        # 判断页面是否正确
        if evidence_mode == "soft":
            if evidence_text in page_text[-1]:
                is_valid = True
        if evidence_mode == "hard":
            for bounds in page_text:
                if evidence_text == bounds[1]:
                    is_valid = True
                    if is_valid:
                        break
        # 点击
        if is_valid:
            target_seq_num = 0
            for bounds in page_text:
                if target_text == bounds[1]:
                    target_seq_num += 1
                    if seq_num == target_seq_num:
                        logger.info(bounds)
                        x1, y1, x2, y2 = bounds[0]
                        x = (x1 + x2) / 2
                        y = (y2 + y2) / 2
                        self.tap(x, y)
                        logger.info(f"tap|target_text:{target_text}|x:{x},y:{y}")
                        sleep(1)

    def click_by_text_partial(self):
        pass

    def back(self):
        pass

    def home(self):
        pass

    def make_app_ready(self, package_name, activity_name):
        is_app_alive = self.is_app_alive(package_name)
        if is_app_alive:
            pass
        else:
            self.start(package_name, activity_name)

    def get_page_text(self, engine="easyocr"):
        img_path = self.screencap()
        if engine == "easyocr":
            from submodules.common.lib.easyocr_ import ocr
            page_text = ocr(img_path)
        elif engine == "cnocr":
            from submodules.common.lib.cnocr_ import get_bounds
            page_text = get_bounds(img_path)
        return page_text


if __name__ == "__main__":
    from constants import app


    def screencap_test():
        from submodules.common.lib.local_paths import project_tmp_images_path

        device = Device()
        device.screencap(path_computer=os.path.join(project_tmp_images_path, "test.png"))


    def screencap_test2():
        from submodules.common.lib.local_paths import project_tmp_images_path

        device_list = adb_.get_device_list()
        device1 = Device(device_list[0][0])
        device2 = Device(device_list[1][0])
        device1.screencap(path_computer=os.path.join(project_tmp_images_path, "test1.png"))
        device2.screencap(path_computer=os.path.join(project_tmp_images_path, "test2.png"))


    def start_test():
        device = Device()
        device.start(app.Toutiao.PACKAGE_NAME, app.Toutiao.MAIN_ACTIVITY)


    def clear_test():
        device = Device()
        device.clear(app.Toutiao.PACKAGE_NAME)


    def grep_test():
        device = Device()
        res = device.grep("android")
        print(res)


    def is_app_alive():
        device = Device()
        res = device.is_app_alive("android")
        res = device.is_app_alive(app.Toutiao.PACKAGE_NAME)
        print(res)


    def install_test():
        device = Device()
        device.install("D:\\apk\\wen_dao.apk")


    def uninstall_test():
        device = Device()
        device.uninstall(app.Wendao.PACKAGE_NAME)


    def get_current_activity_test():
        device = Device()
        res = device.get_current_activity(app.Wendao.PACKAGE_NAME)
        print(res)


    def click_by_text_test():
        device = Device()
        device.click_by_text("同意")


    click_by_text_test()
